#include "stm32f10x.h"
#include "flash.h"
#include <stdio.h>
#include <string.h>
#include "UART3.h"
#define FLASH_START_ADDR 0x0800FC00  // STM32F103C8T6最后一页
#define FLASH_PAGE_SIZE  0x400       // 1KB每页
// 从Flash读取配置并初始化
extern FlashConfig_t flash_config;
#define CONFIG_MAGIC 0x55AA55AA
void init_flash_config(void) {
    // 1. 先从Flash读取配置（尝试获取已保存的配置）
    Flash_ReadConfig(&flash_config);

    // 2. 验证配置是否有效
    if (flash_config.magic == CONFIG_MAGIC && flash_config.is_configured) {
        // 配置有效，打印调试信息
        printf3("init_flash_config: Valid config found - SSID: %s, PWD: %s\r\n", 
               flash_config.ssid, flash_config.pwd);
    } else {
        // 配置无效，初始化默认值
        printf3("init_flash_config: Invalid config, initialize defaults\r\n");
        memset(&flash_config, 0, sizeof(FlashConfig_t));
        flash_config.magic = CONFIG_MAGIC;
        flash_config.is_configured = 0;
    }
}

// Flash擦除函数
void Flash_ErasePage(uint32_t addr) {
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
    FLASH_ErasePage(addr);
    FLASH_Lock();
}

// 写入配置到Flash
void Flash_WriteConfig(FlashConfig_t *config) {
	// 手动添加\0，防止越界
    config->ssid[strlen(config->ssid) + 1] = '\0';
    config->pwd[strlen(config->pwd) + 1] = '\0';
	printf3("ssid:%s,pwd:%s",config->ssid,config->pwd);
    // 擦除页面
    Flash_ErasePage(FLASH_START_ADDR);
    
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
    
    // 写入数据(按32位对齐写入)
	
    uint32_t *data_ptr = (uint32_t*)config;
    uint32_t flash_addr = FLASH_START_ADDR;
    uint32_t data_size = sizeof(FlashConfig_t) / sizeof(uint32_t);
    
    for (uint32_t i = 0; i < data_size; i++) {
        FLASH_ProgramWord(flash_addr, data_ptr[i]);
        flash_addr += 4;
    }
    
    FLASH_Lock();
}

// 从Flash读取配置
void Flash_ReadConfig(FlashConfig_t *config) {
    memcpy(config, (void*)FLASH_START_ADDR, sizeof(FlashConfig_t));
	printf3("Read from Flash - SSID: %s, PWD: %s\r\n", config->ssid, config->pwd);

}
